package com.xmy.cultivate.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * 语音朗读，生成mp3文件
 */
public class VoiceReading {
    public static void main(String[] args) {
        VoiceReading voiceReading = new VoiceReading();
        voiceReading.textToSpeechIO("李小明，签到成功");
    }

    /**
     * 字符串转音频
     *
     * @param str 需要转的文字
     */
    public void textToSpeechIO (String str) {
        ActiveXComponent active = null;
        String path = "E:\\TEST.mp3";
        // 创建 文件输出对象
        active = new ActiveXComponent("Sapi.SpFileStream");//文件输出对象
        Dispatch file = active.getObject();
        // 创建 音频格式对象
        active = new ActiveXComponent("Sapi.SpAudioFormat");//音频格式对象
        Dispatch audio = active.getObject();
        // 创建 语音合成对象
        active = new ActiveXComponent("Sapi.SpVoice");//语音合成对象
        Dispatch voice = active.getObject();
        // 设置 音频格式
        Dispatch.put(audio,"Type",new Variant(39));
        // 设置 输出音频
        Dispatch.putRef(file,"Format",audio);
        // 设置 音频文件输出路径
        Dispatch.call(file,"Open",new Variant(path),new Variant(3),new Variant(true));
        // 音频-->输出音频流
        Dispatch.putRef(voice,"AudioOutputStream",file);
        // 整音量和语速
        Dispatch.put(voice,"Volume",new Variant(100));// 设置音量
        Dispatch.put(voice,"Rate",new Variant(-2));// 设置速率
        // 语音合成（文字-->音频）
        Dispatch.call(voice,"Speak",new Variant(str));
        // 关闭流对，释放资源
        Dispatch.call(file,"Close");
        audio.safeRelease();
        voice.safeRelease();
    }


    /**
     * 字符串文本朗读
     *
     * @param str 要读的文字字符串
     */
    public static void readStr(String str){
        ActiveXComponent ax = new ActiveXComponent("Sapi.SpVoice");
        //运行时输出语音内容
        Dispatch spVoice = ax.getObject();
        //设置音量 0 ~ 100
        ax.setProperty("Volume",new Variant(100));
        //设置朗读速度 -10 ~ +10
        ax.setProperty("Rate",new Variant(-2));
        //执行朗读
        Dispatch.call(spVoice,"Speak",new Variant(str));
    }

}


